package com.inter.controller.travis;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.inter.entity.common.DevicePackageCoverPicture;
import com.inter.entity.common.DevicePackageMarketingStrategy;
import com.inter.entity.common.PartnerProductPackage;
import com.inter.entity.common.PartnerProductRefPackage;
import com.inter.entity.interentity.details.request.RequestDetails;
import com.inter.entity.interentity.details.request.RequestDetailsData;
import com.inter.entity.interentity.details.request.RequestDetailsTradeData;
import com.inter.entity.interentity.details.response.ResponseDetails;
import com.inter.entity.interentity.details.response.ResponseDetailsData;
import com.inter.entity.interentity.details.response.ResponseDetailsRefuelingPackage;
import com.inter.entity.interentity.details.response.ResponseDetailsTradeData;
import com.inter.entity.interentity.utils.UtilsInterfacesPackage;
import com.inter.service.PartnerProductPackageService;
import com.inter.service.SequenceService;
import com.inter.utils.MD5;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 前端商城根据mcc过来取设备详情页的套餐信息的类
 *
 * @author lm
 * @date 2018/8/30
 */
@RestController
@Api(description = "详情套餐")
public class DetailsController {

    private static Logger logger = Logger.getLogger(DetailsController.class);

    @Autowired
    private SequenceService sequenceService;
    @Autowired
    PartnerProductPackageService partnerProductPackageService;

    @CrossOrigin
    @RequestMapping(value = "detailsPage", produces = "application/json;charset=utf-8", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "详情页", response = ResponseDetails.class)
    public String detailsPage(@ApiParam @RequestBody RequestDetails requestDetails) {
        // 1，生成流水号
        String connSeqNo = sequenceService.getPackageTaskNo();
        // 2,生成当前时间戳
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String curtime = df.format(new Date());
        //3,定义要回复的内容
        String jsonString;
        UtilsInterfacesPackage utils = new UtilsInterfacesPackage();
        String requestStr = JSON.toJSONString(requestDetails);
        if (StringUtils.isBlank(requestStr)) {
            logger.info("请求报文不合法:requestStr为空");
            jsonString = utils.dataWeiKong(connSeqNo, curtime);
            return jsonString;
        } else {
            logger.info("前端请求是：" + requestStr);
            RequestDetails requestPackage = JSONArray.parseObject(requestStr, RequestDetails.class);
            String requestSign = requestPackage.getSign();
            if (requestPackage.getSign() == null) {
                logger.info("请求报文不合法:sign为空");
                jsonString = utils.dataWeiKong(connSeqNo, curtime);
                return jsonString;
            } else {
                logger.info("请求的签名是：" + requestSign);
                RequestDetailsData requestData = requestPackage.getData();
                if (requestPackage.getData() == null) {
                    logger.info("请求报文不合法:data为空");
                    jsonString = utils.dataWeiKong(connSeqNo, curtime);
                    return jsonString;
                } else {
                    String partnerCode = requestData.getPartnerCode();
                    String ConnSeqNo = requestData.getConnSeqNo();
                    String tradeTime = requestData.getTradeTime();
                    String token = requestData.getToken();
                    String tradeType = requestData.getTradeType();
                    String lang = requestData.getLang();
                    //lang为空就默认为cn；
                    RequestDetailsTradeData tradeData = requestData.getTradeData();

                    if (StringUtils.isBlank(partnerCode) || StringUtils.isBlank(ConnSeqNo) || StringUtils.isBlank(tradeTime) || StringUtils.isBlank(token) || StringUtils.isBlank(tradeType) || StringUtils.isBlank(lang) || tradeData == null) {
                        logger.info("请求报文不合法:data参数不合法");
                        jsonString = utils.dataWeiKong(connSeqNo, curtime);
                        return jsonString;
                    } else {
                        String coverCountryMcc = requestData.getTradeData().getMcc();
                        String currencyCodeType = requestData.getTradeData().getCurrencyCodeType();
                        if (StringUtils.isBlank(coverCountryMcc) || StringUtils.isBlank(currencyCodeType)) {
                            logger.info("请求报文不合法:mcc或者currencyCodeType为空");
                            jsonString = utils.dataWeiKong(connSeqNo, curtime);
                            return jsonString;
                        } else {
                            // 将请求体json转成String
                            String str = JSON.toJSONString(requestData);
                            // 将Str拿去计算签名
                            String sign = utils.calculateSignature(str);
                            logger.info("计算的签名是：" + sign);
                            if (!requestSign.equalsIgnoreCase(sign)) {
                                logger.info("签名验证失败！");
                                jsonString = utils.publicMessage(ConnSeqNo, partnerCode, tradeTime, token, tradeType);
                                return jsonString;
                            } else {
                                //签名验证通过，代码在这边加
                                List<PartnerProductPackage> partnerProductPackageList = partnerProductPackageService.getProductListByPartnerCodeAndMcc(partnerCode, coverCountryMcc);
                                if (partnerProductPackageList == null || partnerProductPackageList.size() <= 0) {
                                    //如果没有取到相应的值，也要个前端回复一个公众的报文
                                    logger.info("当前渠道无上线套餐！");
                                    jsonString = utils.requestCannotRespondMessage(ConnSeqNo, partnerCode, tradeTime, token, tradeType);
                                    return jsonString;
                                } else {

                                    //签名验证通过,代码在此处添加,下面都是为了准备response的参数

                                    String packageType = null;
                                    String packageCode = null;
                                    String pachageName = null;
                                    String pachageNameEN = null;
                                    String packageDesc = null;
                                    String appScope = null;
                                    String priceType = null;
                                    String packageFlow = null;
                                    String buyType = null;
                                    String minOrderPeriod = null;
                                    String maxOrderPeriod = null;

                                    String mcc = null;
                                    String refPackageName = null;
                                    String refPackageNameEN = null;
                                    String refPackageCode = null;
                                    String refPackageFlow = null;
                                    String refuelingPackageList = null;

                                    String pictureDetails = null;
                                    String packageImgDesc = null;
                                    String packageImgDescEN = null;

                                    String countryNameDetails = null;
                                    String countryNameDetailsEN = null;
                                    String packageTextDesc = null;
                                    String packageTextDescEN = null;
                                    String packageDetailsDesc = null;
                                    String packageDetailsDescEN = null;
                                    String packageDetailsAdd = null;
                                    String packageDetailsAddEN = null;

                                    String strategyCode = null;
                                    String salePriceCNY = null;
                                    String salePriceUSD = null;
                                    String strategyDescCNY = null;
                                    String strategyDescUSD = null;

                                    List<ResponseDetailsTradeData> responseTradeData = new ArrayList<ResponseDetailsTradeData>();
                                    ResponseDetailsTradeData tra = null;

                                    for (PartnerProductPackage product : partnerProductPackageList) {
                                        packageType = product.getPackageType();
                                        packageCode = product.getPackageCode();
                                        pachageName = product.getPackageName();
                                        pachageNameEN = product.getPackageNameEN();
                                        packageDesc = product.getPackageDesc();
                                        appScope = product.getAppScope();
                                        priceType = product.getPriceType();
                                        packageFlow = product.getPackageFlow();
                                        buyType = product.getBuyType();
                                        minOrderPeriod = product.getMinOrderPeriod();
                                        maxOrderPeriod = product.getMaxOrderPeriod();
                                        mcc = product.getCoverCountryMcc();
                                        refuelingPackageList = product.getRefuelingPackageList();

                                        // 1,从CoverPicture表中把图片信息取出来 ,packageCode,partnerCode
                                        List<DevicePackageCoverPicture> pictureList = partnerProductPackageService.getPictureByPartnerCodeAndPackageCode(packageCode, partnerCode);
                                        for (DevicePackageCoverPicture covers : pictureList) {
                                            pictureDetails = covers.getPictureDetails();
                                            packageImgDesc = covers.getPackageImgDesc();
                                            //packageImgDescEN=covers.getPackageImgDescEN();
                                            packageImgDescEN = covers.getPackageImgDesc();

                                            countryNameDetails = covers.getCoverCountrys();
                                            countryNameDetailsEN = covers.getCountryNameDetailsEN();
                                            packageTextDesc = covers.getPackageTextDesc();
                                            packageTextDescEN = covers.getPackageTextDescEN();

                                            packageDetailsDesc = covers.getPackageDetailsDesc();
                                            packageDetailsDescEN = covers.getPackageDetailsDescEN();

                                            packageDetailsAdd = covers.getPackageDetailsAdd();
                                            packageDetailsAddEN = covers.getPackageDetailsAddEN();
                                        }

                                        // 2,从PackageMarketingStrategy表中把营销信息取出来 ,partnerCode
                                        List<DevicePackageMarketingStrategy> strategyList = partnerProductPackageService.getStrategyByPartnerCodeAndPackageCode(packageCode, partnerCode);

                                        for (DevicePackageMarketingStrategy strategy : strategyList) {
                                            salePriceCNY = strategy.getSalePriceCNY();
                                            strategyDescCNY = strategy.getStrategyDescCNY();
                                            strategyCode = strategy.getStrategyCode();
                                            salePriceUSD = strategy.getSalePriceUSD();
                                            strategyDescUSD = strategy.getStrategyDescUSD();
                                        }
                                        //现在拼接回去的数据  //没有加油包

                                        if ("0".equals(refuelingPackageList)) {
                                            //开始拼接tradeData,没有加油包
                                            tra = new ResponseDetailsTradeData();
                                            tra.setPackageType(packageType);
                                            tra.setPackageCode(packageCode);
                                            if ("en".equals(lang)) {
                                                tra.setPackageName(pachageNameEN);
                                            } else {
                                                tra.setPackageName(pachageName);
                                            }
                                            tra.setPackageDesc(packageDesc);
                                            tra.setAppScope(appScope);
                                            tra.setPriceType(priceType);
                                            tra.setPackageFlow(packageFlow);
                                            tra.setBuyType(buyType);
                                            tra.setMinOrderPeriod(minOrderPeriod);
                                            tra.setMaxOrderPeriod(maxOrderPeriod);
                                            //价格回调方案
                                            if ("CNY".equalsIgnoreCase(currencyCodeType) || StringUtils.isBlank(currencyCodeType)) {
                                                if ("1".equals(strategyCode)) {
                                                    //热销，就是正常价格
                                                    tra.setSalePrice(salePriceCNY);
                                                } else {
                                                    //特价
                                                    tra.setSalePrice(strategyDescCNY);
                                                }
                                            } else if ("USD".equalsIgnoreCase(currencyCodeType)) {

                                                if ("1".equals(strategyCode)) {
                                                    //热销，就是正常价格
                                                    tra.setSalePrice(salePriceUSD);
                                                } else {
                                                    //特价
                                                    tra.setSalePrice(strategyDescUSD);
                                                }
                                            }

                                            tra.setMcc(mcc);
                                            tra.setPictureDetails(pictureDetails);
                                            tra.setPackageImgDesc(packageImgDesc);
                                            if ("en".equals(lang)) {
                                                tra.setPackageTextDesc(packageTextDescEN);
                                                tra.setCountryNameDetails(countryNameDetailsEN);
                                                tra.setPackageDetailsDesc(packageDetailsDescEN);
                                                tra.setPackageDetailsAdd(packageDetailsAddEN);
                                            } else {
                                                tra.setPackageTextDesc(packageTextDesc);
                                                tra.setCountryNameDetails(countryNameDetails);
                                                tra.setPackageDetailsDesc(packageDetailsDesc);
                                                tra.setPackageDetailsAdd(packageDetailsAdd);
                                            }

                                            responseTradeData.add(tra);

                                        } //有加油包

                                        else if ("1".equals(refuelingPackageList)) {

                                            List<ResponseDetailsRefuelingPackage> refuelingList = new ArrayList<ResponseDetailsRefuelingPackage>();
                                            ResponseDetailsRefuelingPackage refuelingPackage = null;
                                            //3,把加油包信息取出来
                                            List<PartnerProductRefPackage> RefPackageList = partnerProductPackageService.getRefPackageByPartnerCodeAndPackageCode(packageCode, partnerCode);
                                            for (PartnerProductRefPackage refPackage : RefPackageList) {
                                                refPackageCode = refPackage.getRefPackageCode();
                                                refPackageName = refPackage.getRefPackageName();
                                                refPackageNameEN = refPackage.getRefPackageNameEN();
                                                refPackageFlow = refPackage.getRefPackageFlow();

                                                refuelingPackage = new ResponseDetailsRefuelingPackage();
                                                if ("en".equals(lang)) {
                                                    refuelingPackage.setRefPackageName(refPackageNameEN);
                                                } else {
                                                    refuelingPackage.setRefPackageName(refPackageName);
                                                }
                                                refuelingPackage.setRefPackageCode(refPackageCode);
                                                refuelingPackage.setRefPackageFlow(refPackageFlow);
                                                refuelingList.add(refuelingPackage);
                                            }

                                            //开始拼接tradeData
                                            tra = new ResponseDetailsTradeData();
                                            tra.setPackageType(packageType);
                                            tra.setPackageCode(packageCode);
                                            if ("en".equals(lang)) {
                                                tra.setPackageName(pachageNameEN);
                                            } else {
                                                tra.setPackageName(pachageName);
                                            }
                                            tra.setPackageDesc(packageDesc);
                                            tra.setAppScope(appScope);
                                            tra.setPriceType(priceType);
                                            tra.setPackageFlow(packageFlow);
                                            tra.setBuyType(buyType);
                                            tra.setMinOrderPeriod(minOrderPeriod);
                                            tra.setMaxOrderPeriod(maxOrderPeriod);

                                            //价格回调方案
                                            if ("CNY".equalsIgnoreCase(currencyCodeType)) {
                                                if ("1".equals(strategyCode)) {
                                                    //热销，就是正常价格
                                                    tra.setSalePrice(salePriceCNY);
                                                } else {
                                                    //特价
                                                    tra.setSalePrice(strategyDescCNY);
                                                }
                                            } else if ("USD".equalsIgnoreCase(currencyCodeType)) {

                                                if ("1".equals(strategyCode)) {
                                                    //热销，就是正常价格
                                                    tra.setSalePrice(salePriceUSD);
                                                } else {
                                                    //特价
                                                    tra.setSalePrice(strategyDescUSD);
                                                }
                                            }

                                            tra.setMcc(mcc);
                                            tra.setPictureDetails(pictureDetails);
                                            if ("en".equals(lang)) {

                                                tra.setPackageImgDesc(packageImgDescEN);
                                                tra.setPackageTextDesc(packageTextDescEN);
                                                tra.setCountryNameDetails(countryNameDetailsEN);
                                                tra.setPackageDetailsDesc(packageDetailsDescEN);
                                                tra.setPackageDetailsAdd(packageDetailsAddEN);

                                            } else {

                                                tra.setPackageImgDesc(packageImgDesc);
                                                tra.setPackageTextDesc(packageTextDesc);
                                                tra.setCountryNameDetails(countryNameDetails);
                                                tra.setPackageDetailsDesc(packageDetailsDesc);
                                                tra.setPackageDetailsAdd(packageDetailsAdd);

                                            }
                                            tra.setRefuelingPackage(refuelingList);
                                            responseTradeData.add(tra);
                                        }
                                    }
                                    //循环结束开始拼接data
                                    ResponseDetailsData data = new ResponseDetailsData();
                                    data.setConnSeqNo(ConnSeqNo);
                                    data.setPartnerCode(partnerCode);
                                    data.setToken(token);
                                    data.setTradeTime(curtime);
                                    data.setTradeType(tradeType);
                                    data.setTradeRstCode(1000);
                                    data.setTradeRstMessage("success");
                                    data.setTradeData(responseTradeData);
                                    //赋值ResponsePackageHome
                                    ResponseDetails home = new ResponseDetails();
                                    home.setData(data);
                                    home.setSign(MD5.calcMD5(JSON.toJSONString(data)));

                                    // 返回给调用者的报文
                                    jsonString = JSON.toJSONString(home);
                                    //logger.info("响应报文：" + jsonString);
                                    return jsonString;

                                }

                            }
                        }
                    }
                }
            }

        }
    }
}
